﻿Imports <xmlns:log="urn:myLogConfig">
Imports System.IO
Imports System.Threading
Imports ICSharpCode.SharpZipLib.Tar
Imports ICSharpCode.SharpZipLib.GZip
Imports System.Windows.Threading
Imports System.Net.Mail


Public Class ExecuteMoverUC

    Friend r As MainWindow
    Friend stopBool As Boolean = True
    Friend emailHtmlContent As String
    Dim workingDir As String
    Const msg_launch = "Lancer l'archivage"
    Const msg_stop = "Arrêter l'archivage"
    Const msg_finished = "L'archivage de l'ensemble des chemins est terminé"
    Const msg_cancelled = "L'archivage de l'ensemble des chemins a été arrêté"

    Private icone_error = My.Resources.ic_error.ToImageSource
    Private icone_warning = My.Resources.ic_warning.ToImageSource
    Private icone_accept = My.Resources.ic_accept.ToImageSource
    Private icone_microAccept = My.Resources.micro_accept.ToImageSource
    Private icone_microError = My.Resources.micro_error.ToImageSource

    Private _echoues As Integer
    Public Property echoues() As Integer
        Get
            Return _echoues
        End Get

        Set(ByVal value As Integer)
            _echoues = value
            lbl_echoues.Content = " /  Echoués :" & value & " )"
        End Set
    End Property

    Private _reussis As Integer
    Public Property reussis() As Integer
        Get
            Return _reussis
        End Get

        Set(ByVal value As Integer)
            _reussis = value
            lbl_reussis.Content = "Transferts ( réussis :" & value
        End Set
    End Property



    Private Sub UserControl_Loaded(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles MyBase.Loaded
        r = MainWindow.moiMeme
    End Sub

    Private Sub Button1_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles BTN_launchScan.Click
        If BTN_launchScan.Content = msg_launch Then
            BTN_launchScan.Content = msg_stop
            launchScan()

        Else
            BTN_launchScan.Content = msg_launch
            stopScan()
        End If
    End Sub

    Sub populate()
        Dim lesPlateformes = (From plt In r.masterDoc...<log:plateforme> Select plt).ToList

        For Each unePlateformeXml As XElement In lesPlateformes

            Dim noeudPlateforme As New TreeViewItemWithIcons

            'Ajout des plateformes a la racine du treeview
            Dim unePlateforme As New Plateforme(unePlateformeXml)

            'Ajout des serveurs a la racine du plateformes
            Dim serveursXML = unePlateformeXml.<log:serveur>

            For Each unServeurXml As XElement In serveursXML
                Dim unServeur As New Serveur(unServeurXml, unePlateforme)

                Dim noeudServeur As New TreeViewItemWithIcons

                Dim cheminsXML = unServeurXml.<log:chemin>

                For Each cheminXml As XElement In cheminsXML
                    Dim unChemin As New Chemin(cheminXml, unServeur)
                    Dim noeudChemin As New TreeViewItemWithIcons

                    noeudChemin.HeaderText = unChemin.destDossier
                    noeudChemin.Tag = unChemin
                    noeudChemin.tagXML = cheminXml
                    noeudServeur.Items.Add(noeudChemin)
                Next

                noeudServeur.HeaderText = unServeur.nom
                noeudServeur.Tag = unServeur
                noeudServeur.tagXML = unServeurXml
                noeudPlateforme.Items.Add(noeudServeur)
            Next

            noeudPlateforme.Tag = unePlateforme
            noeudPlateforme.tagXML = unePlateformeXml
            noeudPlateforme.HeaderText = unePlateforme.nom
            TreeView_alltests.Items.Add(noeudPlateforme)
        Next
    End Sub

    Sub launchScan()
        stopBool = False
        TreeView_alltests.Items.Clear()
        populate()
        echoues = 0
        reussis = 0
        setWorkingDir()
        loadingImg.LoadSmile(DirectCast(My.Resources.Resources.loading, System.Drawing.Bitmap))
        loadingImg.StartAnimate()

        For Each noeudPlateforme As TreeViewItemWithIcons In TreeView_alltests.Items

            Dim unePlateforme = DirectCast(noeudPlateforme.Tag, Plateforme)
            noeudPlateforme.Icon = icone_accept
            noeudPlateforme.IsExpanded = True
            setPlateformeText(unePlateforme)
            For Each noeudServeur As TreeViewItemWithIcons In noeudPlateforme.Items
                noeudServeur.IsExpanded = True
                Dim unServeur = DirectCast(noeudServeur.Tag, Serveur)
                noeudServeur.Icon = icone_microAccept

                setServeurText(unServeur)
                For Each noeudChemin As TreeViewItemWithIcons In noeudServeur.Items
                    Dim unChemin = DirectCast(noeudChemin.Tag, Chemin)
                    setCheminText(unChemin)
                    noeudChemin.Icon = icone_microAccept

                    Dim noeudCheminSource As New TreeViewItemWithIcons
                    noeudCheminSource.HeaderText = "Source: " & unChemin.getFullPathSource

                    Dim noeudCheminDestination As New TreeViewItemWithIcons
                    noeudCheminDestination.HeaderText = "Destination: " & unChemin.getFullPathDestination

                    '------------ Source
                    Dim rtnLog = getSourceLogs(unePlateforme, unChemin)
                    updateTreeViewNodes(rtnLog.except, noeudCheminSource, noeudChemin, noeudServeur, noeudPlateforme, unChemin.getFullPathSource, "Source")

                    '------------ Destination
                    Dim excepTestDest = checkDestinationOk(unChemin.getFullPathDestination)
                    updateTreeViewNodes(excepTestDest, noeudCheminDestination, noeudChemin, noeudServeur, noeudPlateforme, unChemin.getFullPathDestination, "Destination")

                    'succès
                    If excepTestDest Is Nothing AndAlso rtnLog.except Is Nothing Then

                        If rtnLog.fichiers IsNot Nothing Then
                            Dim selectedFiles = pathManager.getFilesToMove(rtnLog.fichiers, unServeur.nbJourRetention)
                            moveLogsFiles(unePlateforme, selectedFiles, unChemin, noeudChemin)
                        End If

                        If rtnLog.repertoires IsNot Nothing Then
                            Dim selectedFolders = pathManager.getFoldersToMove(rtnLog.repertoires, unServeur.nbJourRetention)
                            moveLogsFolders(unePlateforme, selectedFolders, unChemin, noeudChemin)
                        End If
                    End If


                    If stopBool Then : Exit Sub : End If
                Next
            Next
        Next
        scanFinished()

    End Sub

    Sub scanFinished()
        loadingImg.LoadSmile(DirectCast(My.Resources.Resources.ic_accept, System.Drawing.Bitmap))
        BTN_launchScan.Content = msg_launch
        stopBool = True
        r.consoleOut.addItim(New ConsoleTypes.msg(msg_finished, ""))
        sendMail()
    End Sub

    Private Function getSourceLogs(plt As Plateforme, chm As Chemin) As SourceLogReturn

        Dim outResult As New SourceLogReturn
        Dim tstart As ParameterizedThreadStart = New ParameterizedThreadStart(Sub()
                                                                                  Try
                                                                                      Using New Impersonator(plt.login, plt.domain, plt.password)
                                                                                          If chm.typeLogs = cst.typeLogs.dossiers Then
                                                                                              outResult.repertoires = New DirectoryInfo(chm.getFullPathSource).GetDirectories
                                                                                          End If
                                                                                          If chm.typeLogs = cst.typeLogs.fichiers Then
                                                                                              outResult.fichiers = New DirectoryInfo(chm.getFullPathSource).GetFiles
                                                                                          End If
                                                                                      End Using
                                                                                  Catch ex As Exception
                                                                                      outResult.except = ex
                                                                                  End Try
                                                                              End Sub)

        Dim theThread = New Thread(tstart)
        theThread.Start()

        Do Until Not theThread.IsAlive
            Thread.Sleep(10)
            r.DoEvents()
        Loop

        Return outResult
    End Function

    Private Function checkDestinationOk(fullPath As String) As Exception

        Dim outException As Exception = Nothing
        Dim credArchivage = r.masterDoc...<log:credArchivage>

        Dim tstart As ThreadStart = New ThreadStart(Sub()
                                                        Try
                                                            Using New Impersonator(credArchivage.@login, credArchivage.@domain, credArchivage.@password)
                                                                pathManager.testFullAccessDirectory(fullPath)
                                                            End Using
                                                        Catch ex As Exception
                                                            outException = ex
                                                        End Try
                                                    End Sub)
        Dim theThread = New Thread(tstart)
        theThread.Start()

        Do Until Not theThread.IsAlive
            Thread.Sleep(10)
            r.DoEvents()
        Loop
        Return outException
    End Function

    Private Sub moveLogsFiles(plt As Plateforme, selectedFiles As List(Of FileInfo), lechemin As Chemin, ByRef noeudChemin As TreeViewItemWithIcons)
        Dim leNoeudChemin = noeudChemin
        Dim tstart As ThreadStart = New ThreadStart(Sub()
                                                        Dim credArchivage = r.masterDoc...<log:credArchivage>
                                                        Dim dates = (From dt In selectedFiles Select dt.getDateFromName Distinct).ToList

                                                        For Each dt In dates
                                                            Dim nomFichierCompressionLocale = dt.toHoroDated & ".tar.gz"
                                                            Dim cheminCompletDestination = lechemin.getFullPathDestination & "\" & nomFichierCompressionLocale

                                                            Try

                                                                'vérifier si l'archive existe déjà en destination
                                                                Using New Impersonator(credArchivage.@login, credArchivage.@domain, credArchivage.@password)
                                                                    If File.Exists(cheminCompletDestination) Then
                                                                        Throw New Exception(" Le fichier archive existe déjà : " & cheminCompletDestination)
                                                                    End If
                                                                End Using

                                                                Dim madt = dt
                                                                Dim filesForDate = (From fic In selectedFiles Select fic Where fic.getDateFromName = madt).ToList
                                                                Dim maxSizeName = (From fic In selectedFiles Select fic.Name.Length).Max

                                                                '----------- Début compression
                                                                Using fs As New FileStream(workingDir & nomFichierCompressionLocale, FileMode.Create, FileAccess.Write, FileShare.None)
                                                                    Using gzipStream As Stream = New GZipOutputStream(fs)
                                                                        Using tarArchive__1 As TarArchive = TarArchive.CreateOutputTarArchive(gzipStream)
                                                                            For Each fichier In filesForDate
                                                                                Dim fichier_x = fichier

                                                                                ' Ajout du noeud fichier
                                                                                leNoeudChemin.Dispatcher.Invoke(DispatcherPriority.Background, New Action(
                                                                                                                Sub()
                                                                                                                    Dim noeudFichier As New TreeViewItemWithIcons
                                                                                                                    noeudFichier.HeaderText = fichier_x.Name & getConstantSpace(fichier_x.Name, maxSizeName, 5) & "(" & fichier_x.getDateFromName.toFrenchShort & ")"
                                                                                                                    noeudFichier.Tag = fichier_x
                                                                                                                    noeudFichier.Icon = My.Resources.logfile.ToImageSource
                                                                                                                    noeudFichier.BringIntoView()
                                                                                                                    leNoeudChemin.Items.Add(noeudFichier)
                                                                                                                End Sub))
                                                                                ' Copie locale
                                                                                Using New Impersonator(plt.login, plt.domain, plt.password)
                                                                                    File.Copy(fichier.FullName, workingDir & fichier.Name, True)
                                                                                End Using


                                                                                leNoeudChemin.Dispatcher.Invoke(DispatcherPriority.Background, New Action(
                                                                                                                Sub()
                                                                                                                    Dim noeudFichier = findNoeudFichierByTag(leNoeudChemin, fichier_x)
                                                                                                                    noeudFichier.HeaderText &= " |-> copié localement"
                                                                                                                End Sub))

                                                                                ' Ajout au .tar du jour
                                                                                Dim _tarEntry As TarEntry = TarEntry.CreateEntryFromFile(workingDir & fichier.Name)
                                                                                _tarEntry.Name = fichier.Name
                                                                                tarArchive__1.WriteEntry(_tarEntry, True)
                                                                            Next
                                                                        End Using
                                                                    End Using
                                                                End Using

                                                                leNoeudChemin.Dispatcher.Invoke(DispatcherPriority.Background, New Action(
                                                                                                                Sub()
                                                                                                                    For Each fic In filesForDate
                                                                                                                        Dim noeudFichier = findNoeudFichierByTag(leNoeudChemin, fic)
                                                                                                                        noeudFichier.HeaderText &= " -> Compressé"
                                                                                                                    Next
                                                                                                                End Sub))

                                                                '----------- copie vers le serveur d'archivage
                                                                Using New Impersonator(credArchivage.@login, credArchivage.@domain, credArchivage.@password)
                                                                    File.Copy(workingDir & nomFichierCompressionLocale, lechemin.getFullPathDestination & "\" & nomFichierCompressionLocale, False)
                                                                End Using

                                                                ' Ajout du noeud fichier
                                                                leNoeudChemin.Dispatcher.Invoke(DispatcherPriority.Background, New Action(
                                                                                                Sub()
                                                                                                    For Each fic In filesForDate
                                                                                                        Dim noeudFichier = findNoeudFichierByTag(leNoeudChemin, fic)
                                                                                                        noeudFichier.HeaderText &= " -> Envoyé vers l'archivage"
                                                                                                        reussis += 1
                                                                                                    Next
                                                                                                End Sub))


                                                                ' Suppression de la source
                                                                For Each fichier In filesForDate
                                                                    Dim fichier_x = fichier
                                                                    Using New Impersonator(plt.login, plt.domain, plt.password)
                                                                        File.Delete(fichier.FullName)
                                                                    End Using

                                                                    leNoeudChemin.Dispatcher.Invoke(DispatcherPriority.Background, New Action(
                                                                                                    Sub()
                                                                                                        Dim noeudDossier = findNoeudFichierByTag(leNoeudChemin, fichier_x)
                                                                                                        noeudDossier.HeaderText &= " |-> Supprimé de la source"
                                                                                                    End Sub))
                                                                Next

                                                                cleanWorkingDir()
                                                                If stopBool Then : Exit Sub : End If

                                                            Catch ex As Exception
                                                                ' Ajout du noeud fichier
                                                                leNoeudChemin.Dispatcher.Invoke(DispatcherPriority.Background, New Action(
                                                                                                Sub()
                                                                                                    Dim noeudFichier As New TreeViewItemWithIcons
                                                                                                    noeudFichier.HeaderText = "Erreur pour " & nomFichierCompressionLocale
                                                                                                    noeudFichier.Tag = "Erreur log : " & ex.Message
                                                                                                    noeudFichier.Icon = icone_warning
                                                                                                    leNoeudChemin.Icon = icone_warning
                                                                                                    DirectCast(leNoeudChemin.Parent, TreeViewItemWithIcons).Icon = icone_warning
                                                                                                    DirectCast(DirectCast(leNoeudChemin.Parent, TreeViewItemWithIcons).Parent, TreeViewItemWithIcons).Icon = icone_warning
                                                                                                    noeudFichier.BringIntoView()
                                                                                                    leNoeudChemin.Items.Add(noeudFichier)
                                                                                                    echoues += 1
                                                                                                End Sub))

                                                            End Try
                                                        Next

                                                    End Sub)
        Dim theThread = New Thread(tstart)
        theThread.SetApartmentState(ApartmentState.STA)
        theThread.Start()

        Do Until Not theThread.IsAlive
            Thread.Sleep(10)
            r.DoEvents()
            If stopBool Then : theThread.Abort() : Exit Sub : End If
        Loop
    End Sub


    Private Sub moveLogsFolders(plt As Plateforme, selectedFiles As List(Of DirectoryInfo), lechemin As Chemin, ByRef noeudChemin As TreeViewItemWithIcons)
        Dim leNoeudChemin = noeudChemin
        Dim tstart As ThreadStart = New ThreadStart(Sub()
                                                        Dim credArchivage = r.masterDoc...<log:credArchivage>
                                                        Dim dates = (From dt In selectedFiles Select dt.getDateFromName Distinct).ToList

                                                        For Each dt In dates
                                                            Dim nomFichierCompressionLocale = dt.toHoroDated & ".tar.gz"
                                                            Dim cheminCompletDestination = lechemin.getFullPathDestination & "\" & nomFichierCompressionLocale
                                                            Try
                                                                'vérifier si l'archive existe déjà en destination
                                                                Using New Impersonator(credArchivage.@login, credArchivage.@domain, credArchivage.@password)
                                                                    If File.Exists(cheminCompletDestination) Then
                                                                        Throw New Exception(" Le fichier archive existe déjà : " & cheminCompletDestination)
                                                                    End If
                                                                End Using

                                                                Dim madt = dt
                                                                Dim foldersForDate = (From fic In selectedFiles Select fic Where fic.getDateFromName = madt).ToList
                                                                Dim maxSizeName = (From fic In selectedFiles Select fic.Name.Length).Max

                                                                '----------- Début compression
                                                                Using fs As New FileStream(workingDir & nomFichierCompressionLocale, FileMode.Create, FileAccess.Write, FileShare.None)
                                                                    Using gzipStream As Stream = New GZipOutputStream(fs)
                                                                        Using tarArchive__1 As TarArchive = TarArchive.CreateOutputTarArchive(gzipStream)
                                                                            For Each dossier In foldersForDate
                                                                                Dim dossier_x = dossier

                                                                                ' Ajout du noeud fichier
                                                                                leNoeudChemin.Dispatcher.Invoke(DispatcherPriority.Background, New Action(
                                                                                                                Sub()
                                                                                                                    Dim noeudFichier As New TreeViewItemWithIcons
                                                                                                                    noeudFichier.HeaderText = dossier_x.Name & getConstantSpace(dossier_x.Name, maxSizeName, 5) & "(" & dossier_x.getDateFromName.toFrenchShort & ")"
                                                                                                                    noeudFichier.Tag = dossier_x
                                                                                                                    noeudFichier.Icon = My.Resources.logFolder.ToImageSource
                                                                                                                    noeudFichier.BringIntoView()
                                                                                                                    leNoeudChemin.Items.Add(noeudFichier)
                                                                                                                End Sub))

                                                                                Dim localDirectory = workingDir & dossier.Name

                                                                                If Directory.Exists(localDirectory) Then
                                                                                    System.IO.Directory.Delete(localDirectory, True)
                                                                                End If


                                                                                ' Copie locale
                                                                                Using New Impersonator(plt.login, plt.domain, plt.password)
                                                                                    pathManager.CopyDirectory(dossier.FullName, localDirectory, True)
                                                                                End Using


                                                                                leNoeudChemin.Dispatcher.Invoke(DispatcherPriority.Background, New Action(
                                                                                                                Sub()
                                                                                                                    Dim noeudDossier = findNoeudDossierByTag(leNoeudChemin, dossier_x)
                                                                                                                    noeudDossier.HeaderText &= " |-> copié localement"
                                                                                                                End Sub))

                                                                                ' Ajout au .tar du jour
                                                                                tarArchive__1.AddDirectoryFilesToTar(localDirectory, True)

                                                                            Next
                                                                        End Using
                                                                    End Using
                                                                End Using

                                                                leNoeudChemin.Dispatcher.Invoke(DispatcherPriority.Background, New Action(
                                                                                                                Sub()
                                                                                                                    For Each fic In foldersForDate
                                                                                                                        Dim noeudDossier = findNoeudDossierByTag(leNoeudChemin, fic)
                                                                                                                        noeudDossier.HeaderText &= " -> Compressé"
                                                                                                                    Next
                                                                                                                End Sub))

                                                                '----------- copie vers le serveur d'archivage
                                                                Using New Impersonator(credArchivage.@login, credArchivage.@domain, credArchivage.@password)
                                                                    File.Copy(workingDir & nomFichierCompressionLocale, cheminCompletDestination, False)
                                                                End Using

                                                                ' Ajout du noeud fichier
                                                                leNoeudChemin.Dispatcher.Invoke(DispatcherPriority.Background, New Action(
                                                                                                Sub()
                                                                                                    For Each doss In foldersForDate
                                                                                                        Dim noeudDossier = findNoeudDossierByTag(leNoeudChemin, doss)
                                                                                                        noeudDossier.HeaderText &= " -> Envoyé vers l'archivage"
                                                                                                        reussis += 1
                                                                                                    Next
                                                                                                End Sub))

                                                                ' Suppression de la source
                                                                For Each dossier In foldersForDate
                                                                    Dim dossier_x = dossier
                                                                    Using New Impersonator(plt.login, plt.domain, plt.password)
                                                                        Directory.Delete(dossier.FullName, True)
                                                                    End Using

                                                                    leNoeudChemin.Dispatcher.Invoke(DispatcherPriority.Background, New Action(
                                                                                                    Sub()
                                                                                                        Dim noeudDossier = findNoeudDossierByTag(leNoeudChemin, dossier_x)
                                                                                                        noeudDossier.HeaderText &= " |-> Supprimé de la source"
                                                                                                    End Sub))
                                                                Next

                                                                cleanWorkingDir()
                                                                If stopBool Then : Exit Sub : End If

                                                            Catch ex As Exception
                                                                ' Ajout du noeud fichier
                                                                leNoeudChemin.Dispatcher.Invoke(DispatcherPriority.Background, New Action(
                                                                                                Sub()
                                                                                                    Dim noeudDossier As New TreeViewItemWithIcons
                                                                                                    noeudDossier.HeaderText = "Erreur pour " & nomFichierCompressionLocale
                                                                                                    noeudDossier.Tag = "Erreur log : " & ex.Message
                                                                                                    noeudDossier.Icon = icone_warning
                                                                                                    leNoeudChemin.Icon = icone_warning
                                                                                                    DirectCast(leNoeudChemin.Parent, TreeViewItemWithIcons).Icon = icone_warning
                                                                                                    DirectCast(DirectCast(leNoeudChemin.Parent, TreeViewItemWithIcons).Parent, TreeViewItemWithIcons).Icon = icone_warning
                                                                                                    noeudDossier.BringIntoView()
                                                                                                    leNoeudChemin.Items.Add(noeudDossier)
                                                                                                    echoues += 1
                                                                                                End Sub))

                                                            End Try
                                                        Next

                                                    End Sub)
        Dim theThread = New Thread(tstart)
        theThread.SetApartmentState(ApartmentState.STA)
        theThread.Start()

        Do Until Not theThread.IsAlive
            Thread.Sleep(10)
            r.DoEvents()
            If stopBool Then
                theThread.Abort()
                Exit Sub
            End If
        Loop
    End Sub
    Private Sub TreeView1Item_selected(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        miniConsole.Document.Blocks.Clear()
        Dim elem As TreeViewItemWithIcons = DirectCast(e.Source, TreeViewItemWithIcons)

        If elem.Tag IsNot Nothing Then

            Select Case elem.Tag.GetType.Name
                Case GetType(String).Name
                    Dim message = DirectCast(elem.Tag, String)
                    If message.StartsWith("Accès ") Then
                        miniConsole.Foreground = Brushes.Green
                    Else
                        miniConsole.Foreground = Brushes.Red
                    End If
                    miniConsole.addTextPair("", message)
                Case GetType(Plateforme).Name
                    Dim plt = DirectCast(elem.Tag, Plateforme)
                    miniConsole.Foreground = Brushes.Black
                    miniConsole.addTextTitle("Plateforme")
                    miniConsole.addTextPair("Nom: ", plt.nom)
                    miniConsole.addTextPair("Destination: ", plt.destination)
                Case GetType(Serveur).Name
                    Dim srv = DirectCast(elem.Tag, Serveur)
                    miniConsole.Foreground = Brushes.Black
                    miniConsole.addTextTitle("Serveur")
                    miniConsole.addTextPair("Nom: ", srv.nom)
                    miniConsole.addTextPair("Jours de rétention: ", srv.nbJourRetention)
                Case GetType(Chemin).Name
                    Dim chm = DirectCast(elem.Tag, Chemin)
                    miniConsole.Foreground = Brushes.Black
                    miniConsole.addTextTitle("Chemin")
                    miniConsole.addTextPair("Type logs: ", chm.typeLogs)
                    miniConsole.addTextPair("Chemin source: ", chm.getFullPathSource)
                    miniConsole.addTextPair("Chemin destination: ", chm.getFullPathDestination)
                Case GetType(FileInfo).Name
                    Dim fichier = DirectCast(elem.Tag, FileInfo)
                    miniConsole.Foreground = Brushes.Black
                    miniConsole.addTextTitle("Fichier de logs")
                    miniConsole.addTextPair("Nom: ", fichier.Name)
                    miniConsole.addTextPair("Date de création: ", fichier.CreationTime.toFrenchComplete)
                    miniConsole.addTextPair("Date de modification: ", fichier.LastWriteTime.toFrenchComplete)
                Case GetType(DirectoryInfo).Name
                    Dim dossier = DirectCast(elem.Tag, DirectoryInfo)
                    miniConsole.Foreground = Brushes.Black
                    miniConsole.addTextTitle("Dossier de logs")
                    miniConsole.addTextPair("Nom: ", dossier.Name)
                    miniConsole.addTextPair("Date de création: ", dossier.CreationTime.toFrenchComplete)
                    miniConsole.addTextPair("Date de modification: ", dossier.LastWriteTime.toFrenchComplete)
            End Select
        End If
    End Sub


    Private Sub testAllPaths_Unloaded(sender As Object, e As System.Windows.RoutedEventArgs) Handles Me.Unloaded
        stopScan()
    End Sub

    Sub stopScan()
        If stopBool = False Then
            loadingImg.LoadSmile(DirectCast(My.Resources.Resources.ic_warning, System.Drawing.Bitmap))
            stopBool = True
            r.consoleOut.addItim(New ConsoleTypes.warning(msg_cancelled, ""))
        End If
    End Sub

    Function getConstantSpace(str As String, max As Int32, desired As Integer) As String
        Dim outstr As String = ""
        Dim nb = max - str.Length + desired

        For i = 0 To nb
            outstr &= "   "
        Next

        Return outstr & vbTab
    End Function

    Function findNoeudFichierByTag(noeudParent As TreeViewItemWithIcons, fichier_x As FileInfo) As TreeViewItemWithIcons
        Dim noeudFichier = (From nf As TreeViewItemWithIcons In noeudParent.Items _
                           Select nf Where GetType(FileInfo).Name = nf.Tag.GetType.Name AndAlso DirectCast(nf.Tag, FileInfo) Is fichier_x).First

        Return noeudFichier
    End Function

    Function findNoeudDossierByTag(noeudParent As TreeViewItemWithIcons, fichier_x As DirectoryInfo) As TreeViewItemWithIcons
        Dim noeudFichier = (From nf As TreeViewItemWithIcons In noeudParent.Items _
                           Select nf Where GetType(DirectoryInfo).Name = nf.Tag.GetType.Name AndAlso DirectCast(nf.Tag, DirectoryInfo) Is fichier_x).First
        Return noeudFichier
    End Function

    Sub updateTreeViewNodes(excepTest As Exception, noeudCheminSub As TreeViewItemWithIcons, noeudChemin As TreeViewItemWithIcons, noeudServeur As TreeViewItemWithIcons, noeudPlateforme As TreeViewItemWithIcons, path As String, typePath As String)
        If excepTest Is Nothing Then
            noeudCheminSub.Icon = icone_microAccept
            noeudCheminSub.Tag = "Accès " & typePath & " OK: " & path
        Else
            noeudCheminSub.Icon = icone_microError
            noeudChemin.Icon = icone_microError
            noeudServeur.Icon = icone_microError
            noeudPlateforme.Icon = icone_error
            noeudCheminSub.Tag = "Erreur accès " & typePath & " : " & excepTest.Message
        End If

        noeudChemin.IsExpanded = True
        noeudChemin.Items.Add(noeudCheminSub)
        noeudCheminSub.BringIntoView()
    End Sub

    Sub cleanWorkingDir()
        Dim workingDirInfo As DirectoryInfo = New DirectoryInfo(workingDir)
        workingDirInfo.purge()
    End Sub

    Sub setWorkingDir()
        Dim rootWorking = (r.masterDoc...<log:repertoireTravail>).Value
        workingDir = If(rootWorking.EndsWith("\"), rootWorking, rootWorking & "\") & "working\"

        If Not Directory.Exists(workingDir) Then
            Directory.CreateDirectory(workingDir)
        End If

        Directory.CreateDirectory(workingDir)
        Directory.SetCurrentDirectory(workingDir)
    End Sub

    Public Sub setPlateformeText(unePlt As Plateforme)
        Console.ForegroundColor = ConsoleColor.Yellow
        Console.WriteLine("---------------------- Plateforme :  " & unePlt.nom & "---------------------- ")
    End Sub

    Public Sub setServeurText(unSrv As Serveur)
        Console.ForegroundColor = ConsoleColor.DarkYellow
        Console.WriteLine("------------------------------------------")
        Console.WriteLine(" Serveur :  " & unSrv.nom)
        Console.WriteLine("------------------------------------------")
    End Sub

    Public Sub setCheminText(unChm As Chemin)
        Console.ForegroundColor = ConsoleColor.White
        Console.WriteLine("Chemin :  " & unChm.getFullPathSource())
    End Sub

    Public Sub sendMail()

        Dim checkMark = "<span class='vert'>&#x2713</span> "
        Dim xMark = "<span class='rouge'>&#x2717</span>"

        For Each noeudPlateforme As TreeViewItemWithIcons In TreeView_alltests.Items

            Dim unePlateforme = DirectCast(noeudPlateforme.Tag, Plateforme)
            emailHtmlContent &= "<div class='stl_plateforme'>"
            If Object.ReferenceEquals(noeudPlateforme.Icon, icone_accept) Then
                emailHtmlContent &= checkMark & " <b>---------------------- Plateforme :  " & unePlateforme.nom & "----------------------</b>"
            Else
                emailHtmlContent &= xMark & " <b>---------------------- Plateforme :  " & unePlateforme.nom & "----------------------</b>"
            End If
           
            For Each noeudServeur As TreeViewItemWithIcons In noeudPlateforme.Items
                Dim unServeur = DirectCast(noeudServeur.Tag, Serveur)
                emailHtmlContent &= "<div class='stl_serveur'>"
                If Object.ReferenceEquals(noeudServeur.Icon, icone_microAccept) Then
                    emailHtmlContent &= checkMark & " ================= Serveur :  " & unServeur.nom & "================"
                Else
                    emailHtmlContent &= xMark & " ================= Serveur :  " & unServeur.nom & "================"
                End If

                For Each noeudChemin As TreeViewItemWithIcons In noeudServeur.Items
                    Dim unChemin = DirectCast(noeudChemin.Tag, Chemin)
                    emailHtmlContent &= "<div class='stl_chemin'>"
                    If Object.ReferenceEquals(noeudChemin.Icon, icone_microAccept) Then
                        emailHtmlContent &= checkMark & " => Chemin"
                    Else
                        emailHtmlContent &= xMark & " => Chemin"
                    End If

                    For Each noeudLog As TreeViewItemWithIcons In noeudChemin.Items
                        If noeudLog.Tag IsNot Nothing Then
                            Select Case noeudLog.Tag.GetType.Name
                                Case GetType(String).Name
                                    Dim message = DirectCast(noeudLog.Tag, String)
                                    If message.StartsWith("Accès ") Then
                                        emailHtmlContent &= "<div class='accesOk'>" & message & "</div>"
                                    End If
                                    If message.StartsWith("Erreur accès ") Then
                                        emailHtmlContent &= "<div class='accesNot'>" & message & "</div>"
                                    End If
                                    If message.StartsWith("Erreur log ") Then
                                        emailHtmlContent &= "<div class='ErrorOnFichier'>" & message & "</div>"
                                    End If
                                Case GetType(FileInfo).Name
                                    Dim fichier = DirectCast(noeudLog.Tag, FileInfo)
                                    emailHtmlContent &= "<div class='fichier'>Fichier: " & fichier.Name & "</div>"
                                Case GetType(DirectoryInfo).Name
                                    Dim dossier = DirectCast(noeudLog.Tag, DirectoryInfo)
                                    emailHtmlContent &= "<div class='dossier'>Dossier: " & dossier.Name & "</div>"
                            End Select
                        End If
                    Next
                    emailHtmlContent &= "</div>"
                Next
                emailHtmlContent &= "</div>"
            Next
            emailHtmlContent &= "</div>"
        Next

        Dim emailSettings = r.masterDoc...<log:emailSettings>
        Dim contenu As String = "<STYLE type='text/css'>" & _
                                ".rouge {color:#cc0000;}" & _
                                ".tresRouge {color:#ff0000;}" & _
                                ".vert {color:#00aa00;}" & _
                                ".fichier {font-size:10px;color:#808080;margin-left:20px;}" & _
                                ".dossier {font-size:10px;color:#808080;margin-left:20px;}" & _
                                ".accesOk {font-size:10px;color:#00aa00;}" & _
                                ".accesNot {font-size:10px;color:#cc0000;}" & _
                                ".ErrorOnFichier {font-size:10px;margin-left:20px;color:#FF0000;}" & _
                                ".stl_plateforme {font-size:14px;font-weight:bold;color:#874800;margin:20px 0 10px 0;border: 1px dotted;}" & _
                                ".stl_serveur {font-size:12px;color:#F28100;margin-left:20px;}" & _
                                ".stl_chemin {font-size:11px;color:#914D44;margin-left:20px;} </STYLE>"

        contenu &= "Résultats déplacement des logs (Log Mover)<br/>" & _
                     "Réussis :" & reussis & " | Echoués :" & echoues
        contenu &= emailHtmlContent

        Dim email As New MailMessage()
        Dim smtpServer As New SmtpClient(emailSettings.@smtpServer, 25)
        email.From = New MailAddress(emailSettings.@sendFrom)
        Dim destinataires = Split(emailSettings.@sendTo, ",")
        For Each desti In destinataires
            email.To.Add(New MailAddress(desti))
        Next

        email.Subject = "Résultats déplacement des logs (Log Mover)"
        email.Body = contenu
        email.IsBodyHtml = True

        Try
            smtpServer.Send(email)
        Catch ex As Exception
            Console.WriteLine("Erreur lors de l'envoi de l'email " & ex.Message)
            r.consoleOut.addItim(New ConsoleTypes.erreur("Erreur lors de l'envoi de l'email ", ex.Message))
        End Try

    End Sub
End Class
